package com.cct.digitalarchapi.common;

import com.cct.digitalarchapi.dao.DigitalArchFilesMapper;
import com.cct.digitalarchapi.pojo.DigitalArchFiles;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @FileName FileUtil
 * @Description 文件工具类
 * @Author Created by chenmingzhe
 * @Date 2023/12/19
 **/
@Slf4j
@Component
public class FileUtil {
    @Autowired
    private Constant constant;
    @Autowired
    private DigitalArchFilesMapper digitalArchFilesMapper;

    public void uploadFile(MultipartFile file,String  archMainCode){
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        String fileSize = size/100 + "KB";
        String fileName = archMainCode + originalFilename;
        String filePath = constant.getUploadPath()+"Archives"+constant.getSplitChar() + fileName;
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件失败：{}", e.getMessage());
        }

        DigitalArchFiles digitalArchFile = new DigitalArchFiles();
        digitalArchFile.setFileName(originalFilename);
        String fileUrl=constant.getIp()+"Archives"+constant.getSplitChar()+fileName;
        digitalArchFile.setArchMainCode(archMainCode);
        digitalArchFile.setFileURL(fileUrl);
        digitalArchFile.setDownloadCount(0);
        digitalArchFile.setFileSize(fileSize);
        digitalArchFilesMapper.addFileRec(digitalArchFile);
    }
}
